<template>
	<view class="menu-box left clearfix">
		<view class="menu-home left" @click="navigatorToHome()">
			<label>
				<uni-icons type="icon-shouye3" size="16" color="#fff" custom-prefix="iconfont"></uni-icons>
			</label>
			<label>首页</label>
		</view>
		
		<view class="menu-items left clearfix">
			
			<view class="menu-item-content left clearfix" v-for="(item,index) in menu" v-show="item && item._id">
				
				<view class="menu-item left clearfix" @click="alertChildrenMenu(item,index)">
					<label class="menu-item-icon">
						<uni-icons :type="item.icon" size="16" color="#666" custom-prefix="iconfont"></uni-icons>
					</label>
					<label class="menu-item-text">{{item.title}}</label>
					<label class="menu-item-right">
						<uni-icons type="bottom" size="16" color="#ccc"></uni-icons>
					</label>
				</view>
				
				<!--下拉菜单-->
				<view class="menu-list-box left clearfix" v-if="showMenu == true && currentIndex == index">
					<view class="menu-list-item left" @click="select(items,indexs)" v-for="(items,indexs) in item.children" v-show="items && items._id">
						{{items.title}}
					</view>
					
				</view>
			</view>
			
			
			
		</view>
	</view>
</template>

<style scoped>
	.menu-list-item:hover{color:#2979ff;}
	.menu-list-item{width:100%;line-height:40px;text-align: center;font-size:14px;color:#444;cursor:pointer;}
	.menu-list-box{width:68%;margin-left:11%;}
	.menu-item-right{width:30px;height:40px;line-height:40px;margin-left:20px;}
	.menu-item-text{width:90px;height:40px;line-height:40px;margin-left:10px;font-size:15px;color:#444;font-weight:400;}
	.menu-item-icon{width:30px;height:40px;line-height:40px;text-align: center;margin-left:20px;}
	.menu-item label{float:left;}
	.menu-item{width:100%;height:40px;margin-left:7%;line-height:40px;margin-top:10px;}
	.menu-items{width:100%;min-height:calc(100% - 90px);margin-top:10px;overflow: auto;}
	.menu-home label:first-child{margin-left:40px;}
	.menu-home label{color:#fff;font-size:14px;margin-left:7px;line-height:36px;float:left;}
	.menu-home{line-height:35px;text-align:center;cursor:pointer;width:60%;height:35px;margin-left:20%;border-radius:10px;margin-top:30px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);}
	.menu-box{width:100%;height:100%;}
</style>

<script>
	var db = uniCloud.database();
	// 1. 获取当前浏览器 URL（在 H5 平台）
	function getCurrentUrl() {
	  if (process.env.UNI_PLATFORM === 'h5') {
	    return window.location.href;
	  }
	  return ''; // 非 H5 平台返回空（如小程序）
	}
	
	// 2. 解析 URL 参数为对象
	function parseUrlParams(url) {
	  const params = {};
	  const searchIndex = url.indexOf('?');
	  
	  if (searchIndex === -1) return params;
	  
	  const queryString = url.substring(searchIndex + 1);
	  const paramPairs = queryString.split('&');
	  
	  paramPairs.forEach(pair => {
	    const [key, value] = pair.split('=');
	    if (key) {
	      params[key] = decodeURIComponent(value || '');
	    }
	  });
	  
	  return params;
	}
	
	// 3. 修改参数并重建 URL
	function updateUrlParam(url, paramName, newValue) {
	  const baseUrl = url.split('?')[0];
	  const params = parseUrlParams(url);
	  
	  // 修改指定参数
	  params[paramName] = newValue;
	  
	  // 重建参数字符串
	  const queryString = Object.entries(params)
	    .map(([key, value]) => 
	      `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
	    )
	    .join('&');
	  
	  return `${baseUrl}?${queryString}`;
	}
	
	// 4. 更新浏览器地址栏（不刷新页面）
	function updateBrowserUrl(newUrl) {
	  if (process.env.UNI_PLATFORM === 'h5' && window.history) {
	    window.history.replaceState(null, null, newUrl);
	  }
	}
	
	export default {
		name:"zmt-menu",
		data() {
			return {
				showMenu:false,
				currentIndex:null,
				menu:[],
				userinfo:{},//登录用户信息
			};
		},
		created() {
			var that = this;
			//验证用户是否登录
			uni.getStorage({
				key:'userinfo-login',
				success:function(e){
					var data = e.data;
					var userinfo = data.userinfo;
					var expire = data.expire;
					var time = new Date().getTime();
					if(!userinfo || !userinfo._id || time > expire){
						
						uni.redirectTo({
							url:'/pages/login/login'
						})
						
					}else{
						
						db.collection('userinfo').where({_id:userinfo._id,is_admin:true}).get({getOne:true}).then(res=>{
							var userinfoData = res.result.data;
							if(!userinfoData || !userinfoData._id){
								//跳转到登录页面重新登录
								uni.redirectTo({
									url:'/pages/login/login'
								})
							}
						}).catch(err=>{
							//跳转到登录页面重新登录
							uni.redirectTo({
								url:'/pages/login/login'
							})
						});
						
						that.userinfo = userinfo;
						//获取系统菜单
						that.getMenu(userinfo.role);
					}
				},
				fail() {
					uni.redirectTo({
						url:'/pages/login/login'
					})
				}
			})
		},
		methods:{
			//查询出对应的菜单
			getMenu(role){
				db.collection('system_menu').where({is_show:true}).orderBy('sort asc').get().then(res=>{
					var data = res.result.data;
					if(role && role.length > 0){
						for(var i = 0;i < data.length;i ++){
							var id = data[i]._id;
							if(role.includes(id)== false){
								delete data[i];
							}
							if(data[i]){
								var children = data[i].children;
								if(children){
									for(var x = 0; x < children.length; x ++ ){
										var childId = children[x]._id;
										if(role.includes(childId)== false || children[x].is_show == false){
											delete data[i].children[x];
										}
									}
								}
								
							}
							
							
						}
					}
					
					this.menu = data;
					
				})
			},
			//跳转到首页
			navigatorToHome(){
				const currentUrl = getCurrentUrl();
				const updatedUrl = updateUrlParam(currentUrl, 'page', 'home');
				updateBrowserUrl(updatedUrl);
				this.$emit('selected',{item:{url:'home'},index:0});
			},
			//点击选中以后
			select(items,indexs){
				const currentUrl = getCurrentUrl();
				const updatedUrl = updateUrlParam(currentUrl, 'page', items.url);
				updateBrowserUrl(updatedUrl);
				this.$emit('selected',{item:items,index:indexs});
			},
			alertChildrenMenu(item,index){
				if(index != this.currentIndex){
					this.showMenu = true;
				}else{
					this.showMenu = !this.showMenu;
				}
				this.currentIndex = index;
			}
		}
	}
</script>

